﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using WebHttpApi.WebHttpApi.Core;
using WebHttpApi.WebHttpApi.HttpApi;

namespace WebHttpApi
{
    public class Global : System.Web.HttpApplication
    {
        //JZP
        static Socket socketClient_Jzq;

        //JZP
        private static void SocketConnect_Jzq()
        {
            try
            {
                string Jzq_IP = System.Configuration.ConfigurationManager.AppSettings["Socket_Jzp_IP"].ToString();
                int Jzq_Port = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["Socket_Jzp_Port"].ToString());

                IPAddress sIP = IPAddress.Parse(Jzq_IP);
                socketClient_Jzq = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint endPoint = new IPEndPoint(sIP, Jzq_Port);
                socketClient_Jzq.Connect(endPoint);

                Thread sendEcho = new Thread(new ThreadStart(HeartBeat_Jzq));
                sendEcho.Start();

                Thread t = new Thread(new ThreadStart(socketReceive_Jzq));
                t.Start();
            }
            catch (Exception)
            {
                socketClient_Jzq.Close();
            }
        }

        //2020-12-09     
        public static void socketReceive_Jzq()
        {
            try
            {
                while (true)
                {
                    Thread.Sleep(100);

                    try
                    {
                        if (socketClient_Jzq.Connected)
                        {
                            byte[] buff = new byte[1024];

                            int length = socketClient_Jzq.Receive(buff);

                            if (length > 0)
                            {
                                DateTime str_dt = DateTime.Now;
                                string rec_info = Encoding.UTF8.GetString(buff, 0, length);

                                if (rec_info != "")
                                {
                                    string str_commid;
                                    string str_resouse;
                                    string str_start;
                                    string str_end;

                                    string data_info = "";

                                    str_resouse = rec_info.ToUpper();
                                    str_start = "68EE";
                                    str_end = "16";

                                    string[] sArray = str_resouse.Split(':');

                                    for (int i = 0; i < sArray.Length; i++)
                                    {
                                        if (sArray[i].IndexOf(str_start) >= 0 && sArray[i].LastIndexOf(str_end) > 4 && sArray[i].Length > 6)
                                        {
                                            try
                                            {
                                                data_info = "68EE" + sArray[i].Substring(sArray[i].IndexOf(str_start) + 4, sArray[i].LastIndexOf(str_end) - 4) + "16";
                                                str_commid = sArray[i - 1].Substring(sArray[i - 1].Length - 10).ToLower();

                                                //2021-02-27 增加更新集中器通讯时间：设备报装“xtsj”
                                                //登录包、心跳包处理
                                                if (data_info.Substring(14, 2) == "40" || data_info.Substring(14, 2) == "41")
                                                {
                                                    string jzq_no = "";

                                                    //集中器编号
                                                    jzq_no = data_info.Substring(4, 10);
                                                    jzq_no = jzq_no.Substring(8, 2) +
                                                             jzq_no.Substring(6, 2) +
                                                             jzq_no.Substring(4, 2) +
                                                             jzq_no.Substring(2, 2) +
                                                             jzq_no.Substring(0, 2);

                                                    bool operator_cx = WebSdkCore.insert_update_delete("update rp_device_bz set xtsj='" +
                                                                                                        str_dt + "' where sbdz='" +
                                                                                                        jzq_no + "'");
                                                }

                                                //2020-12-09                               
                                                //针对控阀指令返回做处理
                                                if (data_info.Substring(14, 2) == "24")
                                                {
                                                    string jzq_no = "";
                                                    string jzq_water_no = "";

                                                    //集中器编号
                                                    jzq_no = data_info.Substring(4, 10);
                                                    jzq_no = jzq_no.Substring(8, 2) +
                                                             jzq_no.Substring(6, 2) +
                                                             jzq_no.Substring(4, 2) +
                                                             jzq_no.Substring(2, 2) +
                                                             jzq_no.Substring(0, 2);

                                                    //水表编号
                                                    jzq_water_no = data_info.Substring(28, 14);
                                                    jzq_water_no = jzq_water_no.Substring(12, 2) +
                                                                   jzq_water_no.Substring(10, 2) +
                                                                   jzq_water_no.Substring(8, 2) +
                                                                   jzq_water_no.Substring(6, 2) +
                                                                   jzq_water_no.Substring(4, 2) +
                                                                   jzq_water_no.Substring(2, 2) +
                                                                   jzq_water_no.Substring(0, 2);

                                                    //控阀结果
                                                    string jzq_kf_result = data_info.Substring(44, 2);
                                                    //执行成功
                                                    if (jzq_kf_result == "00")
                                                    {
                                                        bool operator_cx = WebSdkCore.insert_update_delete("update rp_meter_cx set zxjg = '1',zxsj='" +
                                                                                                            str_dt + "',fhnr='" +
                                                                                                            data_info + "' where ybdz='" +
                                                                                                            jzq_water_no + "' and sbdz='" +
                                                                                                            jzq_no + "' and zxjg='0'");
                                                    }
                                                }
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (SocketException)
                    {
                        break;
                    }
                }
            }
            catch
            {
                return;
            }
        }

        public static void Send_Jzq(string data)
        {
            Thread.Sleep(100);

            try
            {
                data = "FEFEFE" + data;

                if (socketClient_Jzq.Connected)
                {
                    //向 接收中转服务 发数据  
                    byte[] send_msg = new byte[data.Length / 2];

                    for (int i = 0; i < data.Length / 2; i++)
                    {
                        send_msg[i] = Convert.ToByte(data.Substring(i * 2, 2), 16);
                    }

                    socketClient_Jzq.Send(send_msg);
                }
                else
                {
                    Thread.Sleep(30000);
                    SocketConnect_Jzq();
                }
            }
            catch (SocketException)
            {
                socketClient_Jzq.Close();
                Thread.Sleep(30000);
                SocketConnect_Jzq();
            }
        }

        public static void HeartBeat_Jzq()
        {
            while (true)
            {
                Thread.Sleep(30000);

                try
                {
                    if (socketClient_Jzq.Connected)
                    {
                        socketClient_Jzq.Send(Encoding.UTF8.GetBytes("HeartBeat_Jzq"));

                        //2020-12-12
                        //下发未下发控阀指令    

                        //SQL语句
                        string sql = "";
                        //参数
                        string Merer_sbdz;
                        string Merer_jcdbh;
                        string Meter_xylx;
                        string MeterId;
                        string Comm_Type;
                        string CommPam;

                        sql += "select * FROM rp_meter_cx WHERE (ybmc='51' or ybmc='52' or ybmc='53') and zxjg='0' and sbdz IN";
                        sql += "(SELECT sbdz FROM";
                        sql += "(SELECT sbdz FROM rp_meter_cx where (ybmc='51' or ybmc='52' or ybmc='53') and zxjg='0' GROUP BY sbdz having count(sbdz)>=1)a)";
                        sql += "AND KeyId IN";
                        sql += "(SELECT * FROM";
                        sql += "(SELECT min(KeyId) as id FROM rp_meter_cx where (ybmc='51' or ybmc='52' or ybmc='53') and zxjg='0' GROUP BY sbdz HAVING count(sbdz)>=1)b)";

                        System.Data.DataTable Comm_Data = WebSdkCore.select(sql);

                        if (Comm_Data.Rows.Count > 0)
                        {
                            for (int i = 0; i < Comm_Data.Rows.Count; i++)
                            {
                                Merer_sbdz = Comm_Data.Rows[i]["sbdz"].ToString();
                                Merer_jcdbh = Comm_Data.Rows[i]["czy"].ToString();
                                Meter_xylx = Comm_Data.Rows[i]["ybmc"].ToString();
                                MeterId = Comm_Data.Rows[i]["ybdz"].ToString();
                                Comm_Type = Comm_Data.Rows[i]["mllx"].ToString();
                                CommPam = Comm_Data.Rows[i]["mlnr"].ToString();
                                if (CommPam.Substring(56, 2) == "55")
                                {
                                    CommPam = "85";
                                }
                                else
                                {
                                    CommPam = "153";
                                }

                                Thread.Sleep(500);
                                TyLora.Lora_Comm(Merer_sbdz, Merer_jcdbh, Meter_xylx, MeterId, Comm_Type, CommPam);
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(30000);
                        SocketConnect_Jzq();
                    }
                }
                catch (SocketException)
                {
                    socketClient_Jzq.Close();
                    Thread.Sleep(30000);
                    SocketConnect_Jzq();
                }
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            SocketConnect_Jzq();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            socketClient_Jzq.Close();
        }
    }
}